<?php

namespace addons\litestore\controller\api;

use app\common\controller\Api;
use addons\litestore\model\Wxlitestoregoods;
use addons\litestore\model\Litestoregoodsspec;
use app\common\model\OrderAppraise as OrderAppraiseModel;
use think\Db;

class Goods extends Api
{
	protected $noNeedLogin = ['*'];

	public function _initialize()
    {
        parent::_initialize();
    }

	public function detail()
    {
        $request = $this->request->request();
        $goods_id = $this->request->request('goods_id');
        $blogger_id = '';
        if(isset($request['blogger_id']) && !empty($request['blogger_id'])){
            add_ip_visits(request()->ip(),2);
            add_ip_visits_blogger(request()->ip(),$request['blogger_id'],$goods_id);
            $blogger_goods = \think\Db::name('user_goods')
                ->where('deletetime is null')
                ->where('user_id','=',$request['blogger_id'])
                ->where('goods_id','=',$goods_id)
                ->find();
            if(empty($blogger_goods)){
                $this->error('很抱歉，该分享商品信息不存在或已下架');
            }
            $blogger_id = $request['blogger_id'];
        }
        
        //增加点击次数
        Db::name('litestore_goods')->where(['goods_id'=>$goods_id])->setInc('check_num');

		// 商品详情
        $detail = Wxlitestoregoods::detail($goods_id);
        $imgs=[];
        foreach (explode(",",$detail['images']) as $index => $item) {
            $imgs[] = cdnurl($item, true);
        }
        $detail['imgs_url'] = $imgs;

		if (!$detail || $detail['goods_status'] !== '10') {
			$this->error('很抱歉，商品信息不存在或已下架');
        }
        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;

		// 这里对规格的img格式化
        if($specData!=null){
            foreach($specData['spec_list'] as $index => $item){
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image']==='' ? null:cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }

        //商品评论
        $model_temp = new OrderAppraiseModel();
        $pinglun_list = $model_temp
            ->where('goods_id',$goods_id)
            ->where('status','normal')
            ->order('weigh desc')
            ->limit(10)->select();
        foreach($pinglun_list as $k=>$v){
            $imgs1=[];
            if($v['images']){
                foreach (explode(",",$v['images']) as $index => $item) {
                    $imgs1[] = cdnurl($item, true);
                }
            }
            $v['imgs_url'] = $imgs1;
        }
        $pinglun_count = Db::name('order_appraise')->where('goods_id',$goods_id)->where('status','normal')->count();
        $pingluns = Db::name('order_appraise')->where('goods_id',$goods_id)->where('status','normal')->select();
        $star1 = 0;
        $star2 = 0;
        $star3 = 0;
        $star4 = 0;
        $star5 = 0;
        foreach($pingluns as $k=>$v){
            if($v['goods_score'] == 1){
                $star1 ++;
            }
            if($v['goods_score'] == 2){
                $star2 ++;
            }
            if($v['goods_score'] == 3){
                $star3 ++;
            }
            if($v['goods_score'] == 4){
                $star4 ++;
            }
            if($v['goods_score'] == 5){
                $star5 ++;
            }
        }

        //商品是否存在活动中，如果存在，将活动的标签显示出来
        //折扣
        $label_zhekou = \think\Db::name('activity')
            ->where('start_time <= '.time())
            ->where('end_time > '.time())
            ->where('status','1')
            ->where('deletetime is null')
            ->where('goods_ids','like',"%".$goods_id."%")
            ->order('id desc')
            ->value('label');
        $label[] = $label_zhekou;
        //满减、满赠、满送
        $label_full = \think\Db::name('activity_full')
            ->where('start_time <= '.time())
            ->where('end_time > '.time())
            ->where('status','1')
            ->where('deletetime is null')
            ->where('goods_ids','like',"%".$goods_id."%")
            ->order('id desc')
            ->value('label');
        $label[] = $label_full;
        $detail['label'] = $label;

        //历史记录
        $user_id = $this->auth->id;
        $uuid = $this->auth->uuid;
        if(!empty($user_id) || !empty($uuid)){
            if(!empty($user_id)){
                $history_goods = Db::name('history_goods')->where(['user_id'=>$user_id])->where(['goods_id'=>$goods_id])->find();
                if($history_goods){
                    Db::name('history_goods')->where(['id'=>$history_goods['id']])->update(['updatetime'=>time()]);
                }else{
                    $data['user_id'] = $user_id;
                    $data['uuid'] = '';
                    $data['goods_id'] = $goods_id;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('history_goods')->insert($data);
                }
            }else{
                $history_goods = Db::name('history_goods')->where(['uuid'=>$uuid])->where(['goods_id'=>$goods_id])->find();
                if($history_goods){
                    Db::name('history_goods')->where(['id'=>$history_goods['id']])->update(['updatetime'=>time()]);
                }else{
                    $data['user_id'] = 0;
                    $data['uuid'] = $uuid;
                    $data['goods_id'] = $goods_id;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();
                    Db::name('history_goods')->insert($data);
                }
            }
        }

        $this->success('', [
    							'blogger_id'  => $blogger_id,
    							'detail'  => $detail,
                                'specData' => $specData,
                                'pinglun_list' => $pinglun_list,
                                'pinglun_count' => $pinglun_count,
                                'pinglun_star1' => $star1,
                                'pinglun_star2' => $star2,
                                'pinglun_star3' => $star3,
                                'pinglun_star4' => $star4,
                                'pinglun_star5' => $star5,
    					  ]);
    }

    //更多评论
    public function pinglun_more()
    {
        $goods_id = $this->request->request('goods_id');
        $page = $this->request->request('page');
        //商品评论
        $model_temp = new OrderAppraiseModel();
        $pinglun_list = $model_temp
            ->where('goods_id',$goods_id)
            ->where('status','normal')
            ->order('weigh desc')
            ->paginate(8, false, [ 'page' => $page ])
            ->each(function($item){
                $imgs1=[];
                if($item['images']){
                    foreach (explode(",",$item['images']) as $k => $v) {
                        $imgs1[] = cdnurl($v, true);
                    }
                }
                $item['imgs_url'] = $imgs1;
            });

        $this->success('', $pinglun_list);
    }

    //商品列表
    public function category_list(){
        $request = $this->request->request();
        $categoryid = $this->request->request('id');
        $page = $this->request->request('page');
        $sortType = $this->request->request('types');
        $rename = $this->request->request('name');
        $flag = $this->request->request('flag');
        $goods_ids = $this->request->request('gids');

        // 筛选条件
        $filter = [];
        $categorydata = '';
        if(!empty($categoryid)){
            $litestore_category = \think\Db::name('litestore_category')->where('id','=',$categoryid)->find();
            $categorydata = $litestore_category['name'];
            if($litestore_category['pid'] == 0){
                $son_ids = \think\Db::name('litestore_category')->where('pid','=',$categoryid)->column('id');
                $filter['category_id'] = ['in',$son_ids];
            }else{
                $filter['category_id'] = $categoryid;
            }
        }
        if(!empty($rename)){
            $filter['goods_name'] = ['like', '%' . trim($rename) . '%'];
        }
        if(!empty($flag)){
            $filter['flag'] = ['like', '%' . trim($flag) . '%'];
        }
        if(!empty($goods_ids)){
            $filter['goods_id'] = ['in',trim($goods_ids)];
        }
        $blogger_id = '';
        if(isset($request['blogger_id']) && !empty($request['blogger_id'])){
            $blogger_goods_ids = \think\Db::name('user_goods')->where('deletetime is null')->where('user_id','=',$request['blogger_id'])->column('goods_id');
            $filter['goods_id'] = ['in',$blogger_goods_ids];
            $blogger_id = $request['blogger_id'];
        }
        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

         // 排序规则
        $sort = [];
        if ($sortType === 'normal') {
            $sort = ['goods_sort'=> 'desc', 'goods_id' => 'desc'];
        } elseif ($sortType === 'sales') {
            $sort = ['goods_sales' => 'desc'];
        } elseif ($sortType === 'price') {
            $sort = ['goods_min_price' => 'asc'];
        }

        // 商品表名称
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        
        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)->order($sort)
        ->paginate(8, false, [ 'page' => $page ])
        ->each(function($item){
            $item->ImageFrist = cdnurl(explode(",",$item['images'])[0], true);
        });

//        $blistdatarList = [];
//        foreach ($listdata as $index => $item) {
//            $blistdatarList[] = [
//                'id'=> $item['goods_id'],
//                'goods_name' => $item['goods_name'],
//                'image' => cdnurl(explode(",",$item['images'])[0], true),
//                'goods_min_price'=>$item['goods_min_price'],
//                'goods_max_price'=>$item['goods_max_price'],
//                'goods_sales'=>$item['goods_sales']
//            ];
//        }

        $pagedata = $listdata;
        $this->success('', [
                                'blogger_id'  => $blogger_id,
                                'categorydata'  => $categorydata,
//                                'listdata'  => $blistdatarList,
                                'pagedata' => $pagedata,
                          ]);

        
    }

    //历史商品列表
    public function history_list(){
        $user_id = $this->auth->id;
        $uuid = $this->auth->uuid;
        if(!empty($user_id) || !empty($uuid)){
            if(!empty($user_id)){
                $goods_ids = Db::name('history_goods')->where(['user_id'=>$user_id])->order('updatetime desc')->column('goods_id');
            }else{
                $goods_ids = Db::name('history_goods')->where(['uuid'=>$uuid])->order('updatetime desc')->column('goods_id');
            }
        }else{
            $this->success('没有历史记录', []);
        }

        // 筛选条件
        $filter = [];
        if(!empty($goods_ids)){
            $filter['goods_id'] = ['in',$goods_ids];
        }
        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        // 商品表名称
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)
            ->paginate(10)
            ->each(function($item){
                $item->ImageFrist = cdnurl(explode(",",$item['images'])[0], true);
            })->toArray();
        $data = array_column($listdata['data'],null,'goods_id');
        $new_data = [];
        foreach ($goods_ids as $k=>$v){
            $new_data[] = $data[$v];
        }
        $this->success('', $new_data);
    }

}